package com.yunda.teamspinner.localcomponent;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.google.gson.Gson;
import com.yunda.teamspinner.R;
import com.yunda.teamspinner.localcomponent.entity.SpinnerType;
import com.yunda.teamspinner.localcomponent.popupwindow.YdPopWindow;
import com.yunda.teamspinner.localcomponent.sp_interface.ISpinnerItemValue;
import com.yunda.teamspinner.localcomponent.sp_interface.OnSpClickListener;
import com.yunda.teamspinner.localcomponent.sp_interface.OnSpItemClickListener;
import com.yunda.util.DensityUtil;
import com.yunda.util.ScreenUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import static com.yunda.util.CopyUtil.deepCopy;


/**
 * copyright (C), 2022, 运达科技有限公司
 * fileName YdSpinner
 *
 * @author 王玺权
 * date 2022-05-13 14:41
 * description 下拉选择器 参考
 * history https://juejin.cn/post/7014350214471352351
 * https://blog.csdn.net/xiaoerbuyu1233/article/details/122583306
 */
public class YdSpinner<T extends ISpinnerItemValue> extends LinearLayout {
    /**
     * 1、普通选择  2、筛选
     */
    private String type = SpinnerType.SELECT_TYPE;
    private String hintText;
    private TextView view_choose_tv_title;
    private TypedArray typedArray;
    Spinner spinner_rank;
    private int spinnerWidth=0;
    private List<T> mData =new ArrayList<>();
    private List<T> mDataLocal =new ArrayList<>();
    private Context mContext;
    private EditText view_choose_tv_content;
    private YdPopWindow sexPopWindow;
    private RelativeLayout view_choose_rl;
    ImageView iv_view_choose_ic;
    public Boolean flag=false;
    /**
     * 是否单选
     */
    private Boolean isSingle=true;
    /**
     * 是否隐藏图标
     */
    private Boolean isHideIcon=true;
    /**
     * 是否隐藏标题
     */
    private Boolean isHideTitle=false;
    /**
     * 选择位置
     */
    public int selectPos=-1;
    List<T> listSearch=new ArrayList<>();
    private YdSpinner ydSpinner;
    private OnSpItemClickListener<T> onSpItemClickListener;
    private OnSpClickListener onSpClickListener;
    private int textColor;
    private int textHintColor;
    private int textSize;
    private int imgSrc;
    private int backGround;
    //标题文字大小
    private int textTitleSize;

    @RequiresApi(api = Build.VERSION_CODES.O)
    public YdSpinner(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        View inflate = LayoutInflater.from(context).inflate(R.layout.view_spinner, this, true);
        this.mContext=context;

        ydSpinner=this;
        view_choose_tv_title=inflate.findViewById(R.id.view_choose_tv_title);
        view_choose_tv_content=inflate.findViewById(R.id.view_choose_tv_content);
        typedArray = context.obtainStyledAttributes(attrs, R.styleable.ViewSpinner);
        view_choose_rl=findViewById(R.id.view_choose_rl);
        iv_view_choose_ic=findViewById(R.id.iv_view_choose_ic);
        //标题
        String title=typedArray.getString(R.styleable.ViewSpinner_vp_title);
        isHideTitle=typedArray.getBoolean(R.styleable.ViewSpinner_is_hide_title,false);
        view_choose_tv_title.setVisibility(isHideTitle?GONE:VISIBLE);
        //类型
        type=typedArray.getString(R.styleable.ViewSpinner_vp_type);
        textSize=typedArray.getInteger(R.styleable.ViewSpinner_textSize,15);
        textTitleSize=typedArray.getInteger(R.styleable.ViewSpinner_textTitleSize,15);
        imgSrc=typedArray.getResourceId(R.styleable.ViewSpinner_imgSrc,R.mipmap.arrow_down);
        backGround=typedArray.getResourceId(R.styleable.ViewSpinner_backGround,R.drawable.shape_spinner);

        textColor=typedArray.getColor(R.styleable.ViewSpinner_textColor,context.getResources().getColor(R.color.black_666));
        textHintColor=typedArray.getColor(R.styleable.ViewSpinner_textHintColor,context.getResources().getColor(R.color.black_666));


        view_choose_rl.setBackgroundResource(backGround);
        iv_view_choose_ic.setImageResource(imgSrc);
        view_choose_tv_content.setTextSize(DensityUtil.dp2sp(context,textSize));
        view_choose_tv_title.setTextSize(DensityUtil.dp2sp(context,textTitleSize));
        view_choose_tv_content.setTextColor(textColor);
        view_choose_tv_content.setHintTextColor(textHintColor);


        //提示文字
        hintText=typedArray.getString(R.styleable.ViewSpinner_vp_hint);
        if(!TextUtils.isEmpty(hintText)){
            view_choose_tv_content.setHint(hintText);
        }
        //图标
        isHideIcon=typedArray.getBoolean(R.styleable.ViewSpinner_is_hide_ic,false);
        iv_view_choose_ic.setVisibility(isHideIcon?GONE:VISIBLE);
        isSingle=typedArray.getBoolean(R.styleable.ViewSpinner_vp_single,true);


        //不是筛选不可输入数据
        if(!SpinnerType.SERCH_TYPE.equals(type)){
            view_choose_tv_content.setFocusable(false);

            view_choose_tv_content.setInputType(InputType.TYPE_NULL);

            view_choose_tv_content.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(onSpClickListener!=null){
                        onSpClickListener.onSpClickListener(v);
                    }
                }
            });

            view_choose_rl.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(onSpClickListener!=null){
                        onSpClickListener.onSpClickListener(v);
                    }
                }
            });

            iv_view_choose_ic.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(onSpClickListener!=null){
                        onSpClickListener.onSpClickListener(v);
                    }
                }
            });

        }else {
//            view_choose_rl.setOnClickListener(null);
//            view_choose_rl.setEnabled(false);

            view_choose_rl.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(onSpClickListener!=null){
                        onSpClickListener.onSpClickListener(v);
                    }
                }
            });

            iv_view_choose_ic.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(onSpClickListener!=null){
                        onSpClickListener.onSpClickListener(v);
                    }
                }
            });


            view_choose_tv_content.setFocusable(true);
            view_choose_tv_content.setInputType(InputType.TYPE_CLASS_TEXT);
            view_choose_tv_content.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
//                 
                    if (flag) {
                    } else {


                        String keyWork = view_choose_tv_content.getText().toString();
                        listSearch.clear();
                        mData.clear();

                        Log.d("深度拷贝",new Gson().toJson(mDataLocal)+"-----"+keyWork);
                        mData.addAll(mDataLocal);

                        if(TextUtils.isEmpty(keyWork)){
                            Log.d("所有数据",new Gson().toJson(mData)+"-----"+keyWork);
                            //不为空并且包含
                            listSearch.addAll(mData);

                            if (listSearch.size() > 0) {
                                sexPopWindow.updateData(listSearch);
                                sexPopWindow.showPopupWindow(view_choose_rl);
                            }
                        }else {
                            Log.d("所有数据",new Gson().toJson(mData)+"-----"+keyWork);
                            for (int i = 0; i < mData.size(); i++) {
                                //不为空并且包含
                                if (!TextUtils.isEmpty(keyWork)&&((ISpinnerItemValue)mData.get(i)).getItem().toLowerCase().
                                        contains(keyWork.toLowerCase())) {
                                    Log.d("数据对比", new Gson().toJson(mData.get(i)) + "------------" + keyWork);
//                            listSearch.add(new HeroBean(1,((ISpinnerItemValue)mData.get(i)).getItem()));
                                    listSearch.add(mData.get(i));
                                }
                            }

                            if (listSearch.size() > 0) {
                                sexPopWindow.updateData(listSearch);
                                sexPopWindow.showPopupWindow(view_choose_rl);
                            }
                        }


                    }
                }
            });

        }

        view_choose_tv_title.setText(title);
        spinner_rank=new Spinner(mContext);
        Log.d("偏移高度",spinner_rank.getWidth()+"========"+spinner_rank.getMeasuredHeight());
        sexPopWindow=new YdPopWindow(mContext,mData,type,isSingle,this);

        if(type.equals(SpinnerType.SELECT_TYPE)){
            view_choose_tv_content.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(mData.size()==0){
//                        Toast.makeText(mContext, "暂无相关数据", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    sexPopWindow.showPopupWindow(view_choose_rl);
                    if(onSpClickListener!=null){
                        onSpClickListener.onSpClickListener(v);
                        //关闭软件盘
                        ScreenUtil.hideKeyboard(mContext,v.getWindowToken());
                    }
                }
            });
        }else {
            view_choose_tv_content.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(mData.size()==0){
                        Toast.makeText(mContext, "暂无相关数据", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    sexPopWindow.showPopupWindow(view_choose_rl);
                }
            });
        }



        //给选择英雄的spinner添加监听
        spinner_rank.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override //选中的时候执行的方法
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(mContext, ((ISpinnerItemValue)mData.get(i)).getItem(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        view_choose_tv_content.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                show();
            }
        });


    }
    public YdSpinner(Context context) {
        super(context);

    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        this.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if(spinnerWidth==0){
                    Log.d("偏移高度",view_choose_tv_content.getWidth()+"========"+view_choose_tv_content.getMeasuredHeight());
                    spinnerWidth=view_choose_rl.getWidth();
                    spinner_rank.setDropDownVerticalOffset(view_choose_tv_content.getHeight()+8);
                    spinner_rank.setDropDownWidth(view_choose_tv_content.getWidth());
                    sexPopWindow.setWidth(spinnerWidth);
                }
            }
        });
    }

    public List<T> getCheckData(){

        /**
         * 当前类型为筛选时。需要进行判断选择文字是否被修改
         */
        if(type.equals(SpinnerType.SERCH_TYPE)&&sexPopWindow.getCheckBoxList().size()>0){
            ISpinnerItemValue itemModel = (ISpinnerItemValue) sexPopWindow.getCheckBoxList().get(0);
            if(itemModel.getItem().equals(view_choose_tv_content.getText().toString().trim())){
                //文字相同时,标识没有被修改
                return sexPopWindow.getCheckBoxList();
            }else {
                //被修改
                return new ArrayList<>();
            }
        }

        Log.e("返回数据",new Gson().toJson(sexPopWindow.getCheckBoxList())+"??");
        Log.e("返回数据11",new Gson().toJson(sexPopWindow.getCheckBoxList())+"??");

        return sexPopWindow.getCheckBoxList();
    }

    public void setOnSpItemClickListener(OnSpItemClickListener<T> listener){
        this.onSpItemClickListener=listener;
    }

    public void setOnSpClickListener(OnSpClickListener listener){
        this.onSpClickListener=listener;
    }

    public void  setSelectPos(int pos,List<T> heroBeanList){

        if(onSpItemClickListener!=null){

            onSpItemClickListener.onSpItemClick(pos,heroBeanList);
            ScreenUtil.hideKeyboard(mContext,view_choose_tv_content.getWindowToken());
        }
        this.selectPos=pos;
        if(selectPos>=0){
            Log.d("返回数据",new Gson().toJson(heroBeanList)+"???");
            if(isSingle){
                StringBuffer stringBuffer=new StringBuffer();
                for (int i = 0; i <heroBeanList.size() ; i++) {
                    stringBuffer.append(",").append(((ISpinnerItemValue)heroBeanList.get(i)).getItem());
                }
                if(stringBuffer.length()>0){
                    view_choose_tv_content.setText(stringBuffer.toString().substring(1));
                }else {
                    view_choose_tv_content.setText("");
                }

                Log.d("光标到最后","光标到最后");
                view_choose_tv_content.setSelection(view_choose_tv_content.getText().length());




//                 todo 暂时解决 第一次点击无法后续点击 2022年6月28日

                if (flag) {
                } else {


                    String keyWork = view_choose_tv_content.getText().toString();
                    listSearch.clear();
                    mData.clear();

                    Log.d("深度拷贝",new Gson().toJson(mDataLocal)+"-----"+keyWork);
                    mData.addAll(mDataLocal);

                    Log.d("所有数据",new Gson().toJson(mData)+"-----"+keyWork);
                    for (int i = 0; i < mData.size(); i++) {
                        //不为空并且包含
                        if (!TextUtils.isEmpty(keyWork)&&((ISpinnerItemValue)mData.get(i)).getItem().toLowerCase().contains(keyWork.toLowerCase())) {
                            Log.d("数据对比", new Gson().toJson(mData.get(i)) + "------------" + keyWork);
//                            listSearch.add(new HeroBean(1,((ISpinnerItemValue)mData.get(i)).getItem()));
                            listSearch.add(mData.get(i));
                        }
                    }

//                    if (listSearch.size() > 0) {
//                        sexPopWindow.updateData(listSearch);
//                        sexPopWindow.showPopupWindow(view_choose_rl);
//                    }
                }


            }else {
                StringBuffer stringBuffer=new StringBuffer();
                for (int i = 0; i <heroBeanList.size() ; i++) {
                    stringBuffer.append(",").append(((ISpinnerItemValue)heroBeanList.get(i)).getItem());
                }
                if(stringBuffer.length()>0){
                    view_choose_tv_content.setText(stringBuffer.toString().substring(1));
                }else {
                    view_choose_tv_content.setText("");
                }
            }

        }
    }



    public void setmData(List<T> data){
        Log.d("不拷贝",new Gson().toJson(data));
        this.mDataLocal=deepCopy(data);
        this.mData=data;
        sexPopWindow.setData(data);
    }


    /**
     * 展示对话框
     */
    public void show(){
        sexPopWindow.showPopupWindow(view_choose_rl);
    }
    public void show(View view){
        sexPopWindow.showPopupWindow(view);
    }
    /**
     * 选中位置
     * @param position 位置
     */
    public void checkListPosition(List<Integer> position){
        if(position.size()<=0){
            return;
        }
        selectPos=position.get(position.size()-1);
        sexPopWindow.checkListPosition(position);
    }
    public void checkListObj(List<T> data){
        if(data.size()<=0){
            return;
        }
        for (int i = mData.size()-1; i >0 ; i--) {
            for (int j = data.size()-1; j >0 ; j--) {
                if(mData.get(i).getItem().equals(data.get(j).getItem())){
                    selectPos=i;
                    break;
                }
            }
        }

        sexPopWindow.checkListObj(data);
    }

    /**
     * 选中单个位置
     * @param position 位置
     */
    public void checkPosition(int position){
        if(position<0){
            return;
        }
        checkFlag();
        sexPopWindow.checkPosition(position);
    }

    /**
     * 选中单个对象
     * @param obj
     */
    public void checkObj(T obj){

        if(obj==null){
            return;
        }
        checkFlag();
        sexPopWindow.checkObj(obj);
    }

    /**
     * 重置
     */
    public void reset(){
        checkFlag();
        sexPopWindow.reset();
        view_choose_tv_content.setText("");
    }

    /**
     * 复原
     */
    public void recovery(){
        checkFlag();
        sexPopWindow.recovery();
        view_choose_tv_content.setText("");
    }

    public void checkFlag(){
        flag=true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                flag=false;
            }
        },200);
    }

    /**
     * 设置不可以点击
     */
    private T noClickData;
    public void  setNotClick(T bean) {
        noClickData=bean;
        String item = noClickData.getItem();

        view_choose_tv_content.setText(item);
        view_choose_tv_content.setClickable(false);
        view_choose_tv_content.setEnabled(false);
        view_choose_rl.setClickable(false);
        view_choose_rl.setEnabled(false);
        if(backGround==0){
            view_choose_rl.setBackgroundResource(R.drawable.shape_spinner_not_click);
        }else {
            view_choose_rl.setBackgroundResource(backGround);
        }
    }

    /**
     * 获取不可点击
     */
    public T getNoClickData(){
        return noClickData;
    }

    /**
     * 设置背景
     * @param resId 资源文件
     */
    public void setSpBackGround(int resId){
        backGround=resId;
        view_choose_rl.setBackgroundResource(backGround);
    }

    /**
     * 展示右边图标
     * @param resId 资源文件
     * @param show 是否展示
     */
    public void showRightIcon(int resId,Boolean show){
        if(resId!=0){
            iv_view_choose_ic.setImageResource(resId);
        }
        if(show){
            iv_view_choose_ic.setVisibility(VISIBLE);
        }else {
            iv_view_choose_ic.setVisibility(INVISIBLE);
        }

    }

    /**
     * 设置字体颜色
     * @param resId
     */
    public void setSpTextColor(int resId){
        textColor=resId;
        view_choose_tv_content.setTextColor(getResources().getColor(textColor));

    }
    /**
     * 设置字体颜色
     * @param resId
     */
    public void setSpTextHintColor(int resId){
        textHintColor=resId;
        view_choose_tv_content.setHintTextColor(getResources().getColor(textHintColor));

    }

    /**
     * 设置字体大小
     * @param textSize
     */
    public void setSpTextSize(int textSize){
        view_choose_tv_content.setTextSize(DensityUtil.px2sp(mContext,textSize));
    }

    /**
     * 获取输入文字
     * @return
     */
    public EditText getContentView(){
        if(view_choose_tv_content!=null){
            return view_choose_tv_content;
        }
        return null;
    }

    /**
     * 获取布局
     * @return
     */
    public RelativeLayout getLayoutView(){
        if(view_choose_rl!=null){
            return view_choose_rl;
        }
        return null;
    }

}
